# -*- coding: utf-8 -*-
# @time: 2024/6/5 16:57
# @file: bond_YTM_interest_margin
# @author: tyshixi08
import pandas as pd

from get_data.origin_data import *

# 获取3年期AA级信用债YTM
def credit_bond_YTM(flag=1):

    if flag == 1:
        # 获取三年期AA级信用债YTM
        df = pd.read_csv('get_data/原始数据/credit_bond_YTM.csv')[['date', '3Y_AA_YTM']].dropna()

    elif flag == 2:
        # 获取一年期AA级信用债YTM
        df = pd.read_csv('get_data/原始数据/credit_bond_YTM.csv')[['date', '1Y_AA_YTM']].dropna()

    elif flag == 3:
        # 获取三年期A+级信用债YTM
        df = pd.read_csv('get_data/原始数据/credit_bond_YTM.csv')[['date', '3Y_Aplus_YTM']].dropna()

    elif flag == 4:
        # 获取一年期A+级信用债YTM
        df = pd.read_csv('get_data/原始数据/credit_bond_YTM.csv')[['date', '1Y_Aplus_YTM']].dropna()

    return df

# 获取转债YTM
def bond_YTM(code = code_ls(), start_date = month_ls()[0].replace('-','') + '01', end_date = month_ls()[-1].replace('-','') + '01'):
    df = convertible.get_indicators(code, start_date, end_date, fields='yield_to_maturity_pretax').reset_index().rename(columns={'yield_to_maturity_pretax':'yield_to_maturity'})
    df['date'] = pd.to_datetime(df['date']).dt.strftime('%Y-%m-%d')
    return df

# 获取转债YTM利差
def conv_credit_bond_YTM(code=code_ls(), start_date = month_ls()[0].replace('-','') + '01', end_date = month_ls()[-1].replace('-','') + '01', flag = 1):
    df_conv = bond_YTM(code, start_date, end_date)
    df_credit = credit_bond_YTM(flag)
    df_credit['date'] = pd.to_datetime(df_credit['date']).dt.strftime('%Y-%m-%d')
    df = pd.merge(df_conv, df_credit, how = 'outer', on = 'date')
    df = df.dropna()
    df['YTMdelta'] = df['yield_to_maturity'] - df['3Y_AA_YTM']
    df = df[['order_book_id', 'date', 'YTMdelta']]
    return df

# 获取转债YTM利差中位数
def conv_credit_bond_YTM_median(code=code_ls(), start_date = month_ls()[0].replace('-','') + '01', end_date = month_ls()[-1].replace('-','') + '01', flag = 1):
    df = conv_credit_bond_YTM(code, start_date, end_date, flag)
    df_YTMdelta_mid = df.groupby('date')['YTMdelta'].median().reset_index().rename(columns={'YTMdelta':'YTMdelta_mid'})
    return df_YTMdelta_mid.sort_values('date')

# 数据存档
def YTMdelta_mid_save():
    excel_file_path = 'YTMdelta_mid.csv'
    #if os.path.exists('原始数据/' + excel_file_path):
    #    df = pd.read_csv('原始数据/' + excel_file_path)
    #    return df
    #else:
    save_CSV(conv_credit_bond_YTM_median(), 'get_data/原始数据/' + excel_file_path.split('.')[0])
    df = pd.read_csv('get_data/原始数据/' + excel_file_path)
    return df

